export interface Action {
	type: string;
	payload?: any;
}

export type Reducer<State> = (state: State, action: Action) => State;

export type Listener = () => void;

export type Dispatch = (action: Action | AsyncAction) => void;

export type Middleware<State> = (store: CreateStore<State>) => (next: Dispatch) => Dispatch;


export type AsyncAction = (dispatch: Dispatch, getState: () => any) => void;

const localName: string = '__aniStore';

export class CreateStore<State> {
	private reducer: Reducer<State>;
	private state: State;
	private listeners: Listener[];

	constructor(reducer: Reducer<State>, initialState: State) {
		this.reducer = reducer;
		this.state = initialState;
		this.listeners = [];
		this.loadState(); // 尝试从本地存储加载状态
		this.dispatch = this.dispatch.bind(this);
	}

	getState(): State {
		return this.state;
	}

	dispatch(action: Action | AsyncAction): void {

		if (typeof action === 'function') {
			// 处理异步 action
			(action as AsyncAction)(this.dispatch, this.getState);
			return;
		}
		this.state = this.reducer(this.state, action as Action);
		this.listeners.forEach((listener) => listener());
		// this.saveState(); // 状态更新后保存到本地存储
	}

	subscribe(listener: Listener): () => void {
		this.listeners.push(listener);
		return () => {
			this.listeners = this.listeners.filter((l) => l !== listener);
		};
	}

	private saveState(): void {
		wx.setStorageSync(localName, JSON.stringify(this.state));
	}

	private loadState(): void {
		const savedState = wx.getStorageSync(localName);
		if (savedState) {
			this.state = { ...this.state, ...JSON.parse(savedState) };
			this.listeners.forEach((listener) => listener()); // 通知所有订阅者状态已更新
		}
	}
}

export function applyMiddleware<State>(store: CreateStore<State>, middlewares: Middleware[]): void {
	middlewares.slice().reverse().forEach((middleware) => {
		store.dispatch = middleware(store)(store.dispatch);
	});
}

export function logger<State>(store: CreateStore<State>): Middleware {
	return function (next: Dispatch): Dispatch {
		return function (action: Action): void {
			console.log('dispatching', action);
			let result = next(action);
			console.log('next state', store.getState());
			return result;
		};
	};
}

export function thunk<State>(store: CreateStore<State>): Middleware {
	return function (next: Dispatch): Dispatch {
		return function (action: Action | AsyncAction): void {
			if (typeof action === 'function') {
				return (action as AsyncAction)(store.dispatch, store.getState);
			}
			return next(action);
		};
	};
}

export function persistMiddleware<State>(store: CreateStore<State>): Middleware {
	return function (next: Dispatch): Dispatch {
		return function (action: Action): void {
			const result = next(action); // 先让 action 通过其他中间件和 reducer 处理
			const newState = store.getState(); // 获取更新后的状态
			wx.setStorageSync(localName, JSON.stringify(newState)); // 将新状态同步到本地存储
			return result;
		};
	};
}
